<!-- 业务详情 -->
<template>
  <div class="overview-detail">
    <page-header-wrapper>
      <a-card :bordered="false">
        <!-- 详情表单展示 start -->
        <a-row :gutter="48">
          <a-col :md="18" :sm="24">
            <a-descriptions v-if="$auth('PROJECT.BASIC_DETAIL')" title="基本信息"></a-descriptions>
          </a-col>
          <a-col :md="6" :sm="24" align="right">
            <a-button type="primary" style="margin-right: 8px" @click="clickEditMessage" v-if="$auth('PROJECT.PROJECT_EDIT')">编辑</a-button>
            <a-popconfirm okText="删除" cancelText="取消" :title="dynamicTitle" @confirm="deleteProject" @visibleChange="handleVisibleChange">
              <a-button type="danger" v-if="$auth('PROJECT.PROJECT_DELETE') && this.detailsInfo.status != 2">删除</a-button>
            </a-popconfirm>
          </a-col>
        </a-row>
        <a-descriptions v-if="$auth('PROJECT.BASIC_DETAIL')" bordered title="">
          <!-- ******************************接口暂无数据返回先将其注释，否则影响界面展示****************************************** -->
          <a-descriptions-item label="项目名称" :span="2"> {{ detailsInfo.name || '' }} </a-descriptions-item>
          <a-descriptions-item label="项目状态"> {{ detailsInfo.status | enumValueByKey($const.PROJECT_STATUS) }} </a-descriptions-item>
          <a-descriptions-item label="项目编号"> {{ detailsInfo.no || '' }} </a-descriptions-item>
          <a-descriptions-item label="Protocol号"> {{ detailsInfo.protocolNo }} </a-descriptions-item>
          <a-descriptions-item label="立项时间"> {{ detailsInfo.createTime | moment }} </a-descriptions-item>
          <a-descriptions-item label="申办方">{{ detailsInfo.sponsorName }}</a-descriptions-item>
          <a-descriptions-item label="研究分期"> {{ detailsInfo.stage | enumValueByKey($const.SPONSOR_STAGE) }} </a-descriptions-item>
          <!-- 最后一条 业务人员看到的是业务员，其他角色看到的是申办方PM -->
          <a-descriptions-item v-if="isYWAdmin" label="业务人员"> {{ detailsInfo.businessName }} </a-descriptions-item>
          <a-descriptions-item v-else label="申办方项目负责人">{{ detailsInfo.pmName }}</a-descriptions-item>
        </a-descriptions>
        <!-- 项目负责人 -->
        <!-- v-if="isYWAdmin && detailsInfo && detailsInfo.pmName" -->
        <a-descriptions
          bordered
          title="项目负责人"
          v-if="$auth('PROJECT.PROJECT_LEADER_DETAIL') && detailsInfo && detailsInfo.pmName"
          :style="{ margin: '20px 0' }"
          :column="4"
        >
          <a-descriptions-item label="负责人姓名"> {{ detailsInfo.pmName }} </a-descriptions-item>
          <a-descriptions-item label="手机号"> {{ detailsInfo.phone }} </a-descriptions-item>
          <a-descriptions-item label="身份证"> {{ detailsInfo.idCard }} </a-descriptions-item>
          <a-descriptions-item label="操作" v-if="$auth('PROJECT.PROJECT_ADMIN_DELETE') && $const.INVITE_STATUS.INVITE.value == detailsInfo.teamStatus">
            <a-popconfirm okText="删除" cancelText="取消" title="确定要删除吗？" @confirm="deletePm">
              <a-button :loading="removeLoading" size="small" type="danger">删除</a-button>
            </a-popconfirm>
          </a-descriptions-item>
        </a-descriptions>
        <!-- 详情表单展示 end -->
        <!-- 操作按钮 start -->

        <!-- <div v-if="$auth('PROJECT.PROJECT_INVITE') && isYWAdmin && detailsInfo && !detailsInfo.pmName" class="table-operator" :style="{ margin: '20px 0' }"> -->
        <div v-if="$auth('PROJECT.PROJECT_INVITE') && detailsInfo && !detailsInfo.pmName" class="table-operator" :style="{ margin: '20px 0' }">
          <a-button type="primary" icon="plus" @click="inviteResponderAdd()">邀请项目负责人</a-button>
        </div>

        <!-- 费用申请 -->
        <!-- <a-descriptions title="费用申请"></a-descriptions>
        <a-card>
          <div>
            <a-button @click="addApply" type="primary" style="margin-bottom: 25px">
              新增申请
            </a-button>
          </div>
          <div class="table">
            <s-table ref="table" size="default" :rowKey="record => record.id" :columns="columns" :data="loadData">
              <template slot="createTime" slot-scope="text, record">
                {{ record.createTime | moment() }}
              </template>
              <template slot="status" slot-scope="text, record">
                {{ record.status | enumValueByKey($const.COST_APPLY_STATUS) }}
              </template>
              <template slot="operation" slot-scope="text, record">
                <a @click="clickView(record)">查看</a>
                <a-divider type="vertical" />
                <a @click="clickEdit(record)">编辑</a>
              </template>
            </s-table>
          </div>
        </a-card> -->
        <!-- 操作按钮 end -->
        <a-descriptions title="项目管理" style="padding-top: 20px"></a-descriptions>
        <!-- tab切换 start -->
        <a-tabs v-model="activedKey" style="margin-bottom: 20px" @change="callback">
          <a-tab-pane tab="项目成员" :key="1" :forceRender="true" v-if="$auth('PROJECT.PROJECT_MEMBER')">
            <!-- 项目成员 -->
            <Members v-if="activedKey === 1" @cancelMember="cancelMember" ></Members>
          </a-tab-pane>
          <!-- 受试者 -->
          <a-tab-pane tab="受试者" :key="2" :forceRender="true" v-if="$auth('PROJECT.PROJECT_PATIENT')">
            <keep-alive>
              <Subject v-if="activedKey === 2" :datailId="parseInt($route.query.id)"></Subject>
            </keep-alive>
          </a-tab-pane>
          <!-- 访视管理 -->
          <a-tab-pane tab="访视管理" :key="3" :forceRender="true" v-if="$auth('PROJECT.PROJECT_VISIT')">
            <keep-alive>
              <Visit v-if="activedKey === 3"></Visit>
            </keep-alive>
          </a-tab-pane>
          <!-- 审批流程 -->
          <a-tab-pane tab="审批流程" :key="4" :forceRender="true" v-if="$auth('PROJECT.PROJECT_REVIEW')">
            <keep-alive>
              <Approval
                v-if="activedKey === 4"
                :research="researchApprovalInfo"
                :subject="subjectApprovalInfo"
                @update="initApproval"
              ></Approval>
            </keep-alive>
          </a-tab-pane>
          <!-- 费用科目 -->
          <a-tab-pane tab="费用科目" :key="5" :forceRender="true" v-if="$auth('PROJECT.PROJECT_EXPENSE')">
            <keep-alive>
              <Expense v-if="activedKey === 5"></Expense>
            </keep-alive>
          </a-tab-pane>
          <!-- 项目合同 -->
          <a-tab-pane tab="项目合同" v-if="$auth('PROJECT.PROJECT_AGREEMENT')" :key="6" :forceRender="true">
            <keep-alive>
              <Contract v-if="activedKey === 6"></Contract>
            </keep-alive>
          </a-tab-pane>
          <!-- 项目费用 -->
          <a-tab-pane tab="项目费用" v-if="$auth('PROJECT.PROJECT_COST')" :key="7" :forceRender="true">
            <keep-alive>
              <Bill v-if="activedKey === 7" :datailId="parseInt($route.query.id)"></Bill>
            </keep-alive>
          </a-tab-pane>
        </a-tabs>
        <!-- tab切换 end -->

        <!-- 研究者费用 -->
        <!-- <ResearcherList
          :proId="parseInt($route.query.id)"
          :approval="researchApprovalInfo"
          v-if="$auth('PROJECT.PROJECT_FEE') && $auth('PROJECT.PROJECT_FEE_RESEARCHER')"
        /> -->
        <!-- 受试者者费用 -->
        <!-- <ResearcherListSubject
          :proId="parseInt($route.query.id)"
          style="margin-top: 24px"
          :approval="subjectApprovalInfo"
          v-if="$auth('PROJECT.PROJECT_FEE') && $auth('PROJECT.PROJECT_FEE_PATIENT')"
        /> -->
        <!-- 费用审核 -->
        <!-- <CostAuditing style="margin-top: 24px" v-if="$auth('PROJECT.PROJECT_FEE_REVIEW')"></CostAuditing> -->
      </a-card>
    </page-header-wrapper>

    <!-- 邀请项目负责人modal -->
    <MemberModal
      ref="addMemberRef"
      :projectId="projectId"
      :invitedType="invitedType"
      :modalVisible="modalVisible"
      :modalTitle="modalTitle"
      @invitCb="invitCb"
      @closeInvitateModal="closeInvitateModal"
    />
    <!-- 新增/编辑基本信息 -->
    <AddModal
      ref="addModalRef"
      :visible="editVisible"
      @modalOk="updateEdit"
      @modalCancel="closeEditModal"
      :openType="openType"
      :isEditProject="isEditProject"
      :editContent="editContent"
      :phaseListInfo="phaseList"
      :businessList="business"
    />
  </div>
</template>

<script>
import monitor from '@/utils/monitor'
import index from '@/monitor/views/overview/detail/responsible/index'
import moment from 'moment'

import { getProjectDetail, getProjectDelete, getProjectUpdate } from '@/api/overview/contract'
import { getApprovalDetail } from '@/api/overview/approval'
import { deleteLeader } from '@/api/overview/member'
import Members from './components/members'
import Subject from './components/subject'
import Contract from './components/contract'
import Bill from './components/bill'
import Visit from './components/visit.vue'
import Approval from './components/approval'
import Expense from './components/expense'

import AddModal from '@/views/overview/allItems/AddModal'
import AddMemberModal from '@/components/InvitationModal/index'
import MemberModal from '@/components/InvitationModal/MemberModal'
import ResearcherList from '@/views/cost-apply/researcher/ResearcherList'
import ResearcherListSubject from '@/views/cost-apply/subject/SubjectList'
import CostAuditing from '@/views/cost-auditing/index'

import { getSponsorList } from '@/api/system/user'
import { getListAdmin } from '@/api/overview/bill'

import { CURRENT_PROJECT } from '@/store/mutation-types'
import storage from 'store'
import { getUnread } from '@/api/system/message'
const watch = monitor(index)
const tabPaneArr = [
  {
    key: '1',
    tab: '项目成员',
    route: 'index'
  },
  {
    key: '2',
    tab: '受试者'
  },
  {
    key: '3',
    tab: '访视计划'
  },
  {
    key: '4',
    tab: '审批流程'
  },
  {
    key: '5',
    tab: '费用科目'
  },
  {
    key: '6',
    tab: '项目合同'
  },
  {
    key: '7',
    tab: '项目费用'
  }
]
export default {
  props: {},
  components: {
    Members,
    Subject,
    Contract,
    Bill,
    Visit,
    Approval,
    Expense,
    AddModal,
    AddMemberModal,
    MemberModal,
    ResearcherList, // 费用申请 研究者
    ResearcherListSubject, // 费用申请 受试者
    CostAuditing // 审核
  },
  data () {
    return {
      columns: [
        {
          title: 'ID',
          key: 'id',
          dataIndex: 'id'
        },
        {
          title: '研究者ID',
          key: 'ptsNo',
          dataIndex: 'ptsNo'
        },
        {
          title: '申请备注',
          key: 'applyReason',
          dataIndex: 'applyReason'
        },
        {
          title: '申请金额',
          key: 'totalAmount',
          dataIndex: 'totalAmount'
        },
        {
          title: '申请时间',
          key: 'createTime',
          dataIndex: 'createTime',
          scopedSlots: { customRender: 'createTime' }
        },
        {
          title: '当前状态',
          key: 'status',
          dataIndex: 'status',
          scopedSlots: { customRender: 'status' }
        },
        {
          title: '操作',
          dataIndex: 'operation',
          scopedSlots: { customRender: 'operation' }
        }
      ],
      color: 'success', // 状态颜色
      state: null,
      detailsInfo: {}, // 详情列表
      activedKey: 1,
      tabPaneArr, // tab切换数据
      visible: false, // 弹框标识
      confirmLoading: false, // 弹框loading
      form: {},
      userList: [
        {
          key: '用户1',
          value: 1
        },
        {
          key: '用户2',
          value: 2
        }
      ],
      accountList: [],
      roleList: [],
      rules: {
        phone: [{ required: true, message: '请输入正确的手机号', trigger: 'change' }],
        user: [{ required: true, message: '请选择用户', trigger: 'change' }]
      },
      projectId: null,
      invitedType: 1, // 项目负责人 定死的
      modalVisible: false,
      modalTitle: null,
      dynamicTitle: '',
      editVisible: false,
      openType: 1,
      isEditProject: false, // 编辑项目
      phaseList: [], // 申办方列表
      business: [], // 角色列表
      editContent: {},
      researchApprovalInfo: {}, // 研究者审批流
      subjectApprovalInfo: {}, // 受试者审批流
      removeLoading: false,
      pId: null // 项目id 从store中获取的代替从路由中获取
    }
  },
  computed: {
    isYWAdmin () {
      return this.$options.filters.isHasAuth(this.$const.ROLE_TYPE.YW_ADMIN.value)
    }
  },
  created () {
    const pro = storage.get(CURRENT_PROJECT)
    if (pro != null && pro.length > 0) {
      const project = JSON.parse(pro)
      this.pId = project.id
      this.$route.query.id = this.pId
    }

    getUnread({ proId: this.pId }).then(res => {
      this.$globalVue.$emit('unReadMsgCount', res)
    })
  },
  mounted () {
    this.detailsList()
    this.init()
    this.getRoleList()
    this.getSponsorList()

    this.browsePage()
    this.browseMemberPage()
    this.initTabs()
    this.initApproval()
    if (this.$store.state.app.activeKey) {
      this.activedKey = this.$store.state.app.activeKey
    }
  },
  methods: watch({
    // 获取审批流详情
    async initApproval () {
      if (!this.$auth('PROJECT.PROJECT_REVIEW')) return
      this.researchApprovalInfo = await getApprovalDetail({
        proId: this.$route.query.id,
        type: 1
      })
      this.subjectApprovalInfo = await getApprovalDetail({
        proId: this.$route.query.id,
        type: 2
      })
    },
    // 根据权限初始化项目管理的tabs
    initTabs () {
      const arr = [
        this.$auth('PROJECT.PROJECT_MEMBER'),
        this.$auth('PROJECT.PROJECT_PATIENT'),
        this.$auth('PROJECT.PROJECT_VISIT'),
        this.$auth('PROJECT.PROJECT_REVIEW'),
        this.$auth('PROJECT.PROJECT_EXPENSE'),
        this.$auth('PROJECT.PROJECT_AGREEMENT'),
        this.$auth('PROJECT.PROJECT_COST')
      ]
      this.activedKey = arr.findIndex(Boolean) + 1
    },
    // 请求申办方列表
    getSponsorList () {
      getSponsorList({ code: 10001011 }).then(res => {
        this.phaseList = res
      })
    },
    // 请求角色列表
    getRoleList () {
      getListAdmin({
      }).then(res => {
        this.business = res
      })
    },
    init () {},
    // 点击查看
    clickView (record) {
      console.log('点击了查看', record)
    },
    clickEdit (record) {
      console.log('点击编辑', record)
    },
    detailsList () {
      const datailsId = this.$route.query.id
      if (datailsId) {
        getProjectDetail({
          id: Number.parseFloat(datailsId)
        }).then(res => {
          this.detailsInfo = res
          const { protocolNo, name, status, stage, budget, no, contractNo, buildTime, createrId, businessName } = res
          const sponsorIds = res.sponsorIds.split(',').map(Number) // 注：后端返回的是个字符串需将其转为数组(split分割后是个string数组，map方法将其转为number数组)
          this.editContent = { protocolNo, name, sponsorIds, status, stage, budget, no, contractNo, buildTime, createrId, businessName }
          this.editContent.buildTime = moment(this.editContent.buildTime).format('YYYY-MM-DD')
        })
      }
    },
    callback (key) {
      if (key === 1) {
        this.browseMemberPage()
      } else if (key === 2) {
        this.browseSubjectPage()
      } else if (key === 3) {
        this.browseVisitPage()
      } else if (key === 4) {
        this.browseApprovalPage()
      } else if (key === 5) {
        this.browseExpensePage()
      } else if (key === 6) {
        this.browseContractPage()
      } else if (key === 7) {
        this.browseBillPage()
      }
      this.$store.commit('changeActiveKey', key)
    },
    // 邀请项目负责人
    inviteResponderAdd () {
      // this.visible = true
      // this.$refs.addMemberRef.toggleModal() // 显示添加对话框
      this.modalVisible = true
      this.projectId = this.$route.query.id
      this.modalTitle = '添加项目负责人'
      this.$refs.addMemberRef.getNewRolesList()
      // this.$forceUpdate()
    },
    // 新增确定
    onSubmit () {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          this.confirmLoading = true
          new Promise(resolve => {
            setTimeout(() => {
              resolve()
            }, 800)
          }).then(() => {
            this.confirmLoading = false
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    closeInvitateModal (val) {
      this.modalVisible = false
    },
    // 点击删除项目
    deleteProject () {
      // if (this.detailsInfo.status === 2) {
      //   this.$message.error('项目进行中禁止删除')
      //   return false
      // }
      getProjectDelete({
        id: this.$route.query.id,
        status: this.detailsInfo.status
      }).then(res => {
        this.$message.success('删除成功')
        this.$router.push({ name: 'All' })
      })
    },
    // 判断状态是否可删除
    handleVisibleChange () {
      if (this.detailsInfo.status === 2) {
       this.dynamicTitle = '项目进行中禁止删除'
      } else {
        this.dynamicTitle = '是否要删除此项目？'
      }
    },
    // 点击修改信息
    clickEditMessage () {
      this.editVisible = true
      this.$refs.addModalRef.title = '编辑项目'
      this.isEditProject = true
      console.log('点击了编辑')
    },
    // 关闭编辑基本信息弹窗
    closeEditModal () {
      this.editVisible = false
    },
    // 提交修改
    updateEdit (e) {
      delete e.buildTime
      delete e.businessName
      this.editMessage()
      getProjectUpdate({ ...e, id: this.$route.query.id })
        .then(res => {
          this.$message.success('信息修改成功')
          this.editVisible = false
          this.detailsList()
        })
    },
    cancelMember () {
      this.detailsList()
    },
    // 页面浏览埋点
    browsePage () {},
    // 基本信息编辑埋点
    editMessage () {},
    // 项目成员页面浏览埋点
    browseMemberPage () {},
    // 受试者页面浏览埋点
    browseSubjectPage () {},
    // // 访视计划页面浏览埋点
    browseVisitPage () {},
    // // 审批流程页面浏览埋点
    browseApprovalPage () {},
    // // 费用科目页面浏览埋点
    browseExpensePage () {},
    // // 项目合同页面浏览埋点
    browseContractPage () {},
    // // 项目费用页面浏览埋点
    browseBillPage () {},
    deletePm () {
      this.removeLoading = true
      deleteLeader({ id: this.detailsInfo.teamId }).then(res => {
        this.removeLoading = false
        this.detailsList()
        this.$message.success('删除成功')
      }).catch(_ => {
        this.removeLoading = false
      })
    },
    invitCb () {
      this.detailsList()
      if (this.activedKey === 1) {
        this.activedKey = 0
        setTimeout(() => {
          this.activedKey = 1
        }, 200)
      }
    }
  })
}
</script>
<style scoped lang="scss"></style>
